<template>
  <div class="common-layout" :class="{ 'blur-background': isDialogOpen }">
    <el-container>
      <el-container>
        <!-- 侧边栏部分 -->
        <el-aside :width="isCollapse ? '68px' : '220px'" class="app-aside">
          <h3>SWPT</h3>


          <!-- 菜单 -->
          <el-menu :collapse="isCollapse" class="el-menu-vertical-demo" :default-active="activeMenu" router
            @select="handleMenuSelect">

            <!-- 租户&项目管理模块 -->
            <el-sub-menu v-if="hasTenantProjectManagement" index="tenant-project-management">
              <template #title>
                <el-icon>
                  <OfficeBuilding />
                </el-icon>
                <span class="fonts">租户&项目管理</span>
              </template>
              <el-menu-item v-for="item in tenantProjectManagementMenus" :key="item.index" :index="item.index">
                <!-- 动态绑定图标 -->
                <el-icon>
                  <component :is="item.icon" />
                </el-icon>
                <span>{{ item.title }}</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 造价综合评估模块 -->
            <el-sub-menu v-if="hasCostEvaluation" index="cost-evaluation">
              <template #title>
                <el-icon>
                  <SetUp />
                </el-icon>
                <span class="fonts">造价综合评估</span>
              </template>
              <el-menu-item v-for="item in costEvaluationMenus" :key="item.index" :index="item.index">
                <el-icon>
                  <component :is="item.icon" />
                </el-icon>
                <span>{{ item.title }}</span>
              </el-menu-item>
            </el-sub-menu>

            <!-- 报告生成与展示模块 -->
            <el-sub-menu v-if="hasReportGeneration" index="report-generation">
              <template #title>
                <el-icon>
                  <Document />
                </el-icon>
                <span>报告生成与展示</span>
              </template>
              <el-menu-item v-for="item in reportGenerationMenus" :key="item.index" :index="item.index">
                <el-icon>
                  <component :is="item.icon" />
                </el-icon>
                <span>{{ item.title }}</span>
              </el-menu-item>
            </el-sub-menu>

          </el-menu>

        </el-aside>

        <!-- 主体内容部分 -->
        <el-container class="el-right">
          <!-- 页头部分 -->
          <el-header class="app-header" :style="headerStyle">
            <div class="header-content">

              <div @click="toggleCollapse" style="margin-top: 3px;">
                <el-icon v-if="isCollapse" style="font-size: 26px;">
                  <Expand></Expand>
                </el-icon>
                <el-icon v-else style="font-size: 26px;">
                  <Fold />
                </el-icon>

              </div>

              <div>
                <el-dropdown placement="bottom-end" @command="handleCommand">
                  <el-avatar :src="avatar" class="el-dropdown__box" />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="personInfo" :icon="User">基本资料</el-dropdown-item>
                      <el-dropdown-item command="updateInfo" :icon="Crop">修改信息</el-dropdown-item>
                      <el-dropdown-item command="updatePwd" :icon="EditPen">重置密码</el-dropdown-item>
                      <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>

            </div>

            <!-- 标签页 -->
            <div>
              <el-tabs v-model="editableTabsValue" type="card" editable class="custom-tabs" @edit="handleTabsEdit"
                @tab-click="handeTabsClick">
                <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-header>
          <el-main class="main-container">
            <div style="height: 106px; color:#fff;"></div>
            <!-- 监听子组件事件 -->
            <router-view :key="editableTabsValue" @dialogUpdated="handleDialog" />
            <div>
              <SseComponent />
            </div>
          </el-main>
          <!-- 用户信息展示 -->
          <el-dialog v-model="showUserInfoDialog" title="个人信息" width="25%">
            <div>
              <el-avatar :src="userForm?.avatar" size="large" style="text-align: center;" />
              <div style="margin-top: 20px; width: 100%;">
                <div class="info-row">
                  <strong class="label">用户名:</strong>
                  <span class="value">{{ userForm?.username }}</span>
                </div>
                <div class="info-row">
                  <strong class="label">昵称:</strong>
                  <span class="value">{{ userForm?.nickname }}</span>
                </div>
                <div class="info-row">
                  <strong class="label">手机号码:</strong>
                  <span class="value">{{ userForm?.phone }}</span>
                </div>
                <div class="info-row">
                  <strong class="label">用户邮箱:</strong>
                  <span class="value">{{ userForm?.email }}</span>
                </div>

                <div class="info-row">
                  <strong class="label">当前角色:</strong>
                  <span class="value">
                    <el-tag v-for="role in userForm?.authorityStrings" :key="role" type="primary"
                      style="margin-right: 5px;">
                      {{ role }}
                    </el-tag>
                  </span>
                </div>
                <div class="info-row">
                  <strong class="label">所属租户:</strong>
                  <span class="value">{{ userForm?.tenantName }}</span>
                </div>

              </div>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showUserInfoDialog = false" style="margin-left: 230px;">确定</el-button>
            </span>
          </el-dialog>
          <!-- 修改密码对话框 -->
          <el-dialog v-model="showChangePasswordDialog" title="修改密码" width="25%">
            <div style="padding: 20px;">
              <!-- 原密码输入框 -->
              <el-form-item label="原密码">
                <el-input v-model="passwords.oldPassword" type="password" placeholder="请输入原密码"
                  autocomplete="current-password" style="width: 200px;">
                </el-input>
              </el-form-item>
              <!-- 新密码输入框 -->
              <el-form-item label="新密码">
                <el-input v-model="passwords.newPassword" type="password" placeholder="请输入新密码"
                  autocomplete="new-password" style="width: 200px;">
                </el-input>
              </el-form-item>
              <!-- 确认新密码输入框 -->
              <el-form-item label="确认新密码">
                <el-input v-model="passwords.confirmPassword" type="password" placeholder="请再次输入新密码"
                  autocomplete="new-password" style="width: 170px;">
                </el-input>
              </el-form-item>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showChangePasswordDialog = false" style="margin-left: 180px;">取消</el-button>
              <el-button type="primary" @click="handleSubmit">确定</el-button>
            </span>
          </el-dialog>

          <el-dialog v-model="dialogVisible" title="修改信息" width="400" :before-close="handleClose" append-to-body
            :close-on-click-modal="false" :close-on-press-escape="false">


            <template #footer>
              <div class="dialog-footer">
                <el-button plain type="info" @click="dialogVisible = false">取消</el-button>
                <el-button plain type="primary" @click="update()">
                  确认
                </el-button>
              </div>
            </template>

            <el-form ref="dialogForm" style="width: 500px; margin-left: 30px;" :model="userForm" :rules="rules"
              label-width="auto" class="el-form" status-icon>
              <el-form-item label="用户名" prop="username" required>
                <el-input v-model="userForm.username" style="width: 200px;" readonly/>
              </el-form-item>
              <el-form-item label="昵称" prop="nickname" >
                <el-input v-model="userForm.nickname" style="width: 200px;" />
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="userForm.gender" style="width: 200px;">
                  <el-radio value="0">女</el-radio>
                  <el-radio value="1">男</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="手机号" prop="phone" required>
                <el-input v-model="userForm.phone" style="width: 200px;" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email" required>
                <el-input v-model="userForm.email" style="width: 200px;" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="userForm.remark" style="width: 200px;" />
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-container>
      </el-container>
    </el-container>
  </div>




</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  ElContainer, ElAside, ElHeader, ElMain, ElMenu, ElMenuItem, ElSubMenu, ElIcon, ElTabs, ElTabPane, ElDropdown,
  ElDropdownMenu, ElDropdownItem, ElAvatar, ElMessageBox, ElMessage
} from 'element-plus';
import { User, Crop, EditPen, SwitchButton } from '@element-plus/icons-vue';
import avatar from '../assets/avater.jpg'; // 确保路径正确
import type { TabPaneName, TabsPaneContext, FormInstance,FormRules } from 'element-plus'
import { useTokenStore } from "../stores/token.ts";
import { useUserStore } from "../stores/UserStore";
import { Userlogout, updateUser ,updatePwd, getLoginInfo} from '../api/Tenant/userApi.ts';
import SseComponent from '../components/Tenant/SseComponent.vue';
import { UserDTO } from '../type/User.ts';
const tokenStore = useTokenStore()
const userStore = useUserStore()
const router = useRouter();
const route = useRoute();


// 定义类型
interface Tab {
  title: string;//标签标题
  name: string;//路由名称
}
interface MenuItem {
  index: string;
  title: string;
  icon: string;
  roles: string[]; // 允许访问的角色列表
}
const isCollapse = ref(false); // 控制侧边栏的展开/收起
const activeMenu = ref<string>(''); // 当前选中的菜单项
const editableTabsValue = ref<string>(''); // 当前选中的 tab 路由
const editableTabs = reactive<Tab[]>([]); // 动态生成的 tabs



// 切换侧边栏的展开/收起
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value;
};

// 导航菜单列表（可以进一步优化为动态加载）添加 roles 属性
const menuList: MenuItem[] = [
  {
    index: '/home/tenant/user',
    title: '用户管理',
    icon: 'User',
    roles: ["ROLE_admin", "ROLE_super"],
  },
  {
    index: '/home/tenant/manage',
    title: '租户管理',
    icon: 'School',
    roles: ["ROLE_admin", "ROLE_super"],
  },
  {
    index: '/home/tenant/project',
    title: '项目管理',
    icon: 'Files',
    roles: ["ROLE_admin", "ROLE_super"],
  },
  {
    index: '/home/tenant/task',
    title: '任务管理',
    icon: 'Trophy',
    roles: ["ROLE_admin", "ROLE_super"],
  },
  {
    index: '/home/tenant/notice',
    title: '通知管理',
    icon: 'Notification',
    roles: ["ROLE_admin", "ROLE_super", "ROLE_user"],
  },
  {
    index: '/home/cost/basicInfo',
    title: '成本基本信息',
    icon: 'Memo',
    roles: ["ROLE_appraiser", "ROLE_super"],
  },
  {
    index: '/home/cost/calculation',
    title: '成本计算',
    icon: 'Timer',
    roles: ["ROLE_appraiser", "ROLE_super"],
  },
  {
    index: '/home/report/generate',
    title: '生成评估报告',
    icon: 'Aim',
    roles: ["ROLE_auditor", "ROLE_super"],
  },
  {
    index: '/home/report/review',
    title: '报告评审',
    icon: 'Finished',
    roles: ["ROLE_auditor", "ROLE_super"],
  },
  {
    index: '/home/report/Kanban',
    title: '数据看板',
    icon: 'PieChart',
    roles: ["ROLE_admin", "ROLE_super"],
  }
];

// 计算过滤后的菜单列表
const filteredMenuList = computed(() => {
  const list = menuList.filter(menu => {
    // 如果菜单项没有 roles 属性，则默认所有角色可见
    if (!menu.roles || menu.roles.length === 0) {
      return true;
    }
    // 检查用户是否具有访问该菜单的角色
    const premissions = userStore.userInfo.authorityStrings || [];
    return menu.roles.some(role => premissions.indexOf(role) >= 0);
  });
  return list;
});

// 分组菜单项
const tenantProjectManagementMenus = computed(() => {
  return filteredMenuList.value.filter(menu =>
    menu.index.startsWith('/home/tenant')
  );
});

const costEvaluationMenus = computed(() => {
  return filteredMenuList.value.filter(menu =>
    // menu.index.startsWith('/home/cost/basicInfo') ||
    menu.index.startsWith('/home/cost/calculation')
  );
});

const reportGenerationMenus = computed(() => {
  return filteredMenuList.value.filter(menu =>
    menu.index.startsWith('/home/report')
  );
});

// 判断用户是否有访问某个子菜单组的权限
const hasTenantProjectManagement = computed(() => {
  return tenantProjectManagementMenus.value.length > 0;
});


const hasCostEvaluation = computed(() => {
  return costEvaluationMenus.value.length > 0;
});

const hasReportGeneration = computed(() => {
  return reportGenerationMenus.value.length > 0;
});

// 处理菜单选择事件
const handleMenuSelect = (index: string) => {
  if (!index) return;
  // 检查是否已经有这个 tab，如果没有则添加
  const existingTab = editableTabs.find((tab) => tab.name === index);
  if (!existingTab) {
    const newTab: Tab = {
      title: getTabTitle(index),
      name: index,
    };
    editableTabs.push(newTab);
  }
  editableTabsValue.value = index; // 切换到新添加的 tab
  router.push(index); // 直接导航到对应路由
};

// 根据菜单项的 index 获取对应的标题
const getTabTitle = (index: string): string => {
  const found = menuList.find((menu) => menu.index === index);
  return found ? found.title : '新标签页';
};
// 导航到对应的路由
const navigateToRoute = (index: string) => {
  router.push(index);
};
// 处理标签页编辑（关闭）
const handleTabsEdit = (
  targetName: TabPaneName | undefined,
  action: 'remove' | 'add'
) => {
  if (action === 'remove') {
    const tabIndex = editableTabs.findIndex((tab) => tab.name === targetName);
    if (tabIndex !== -1) {
      editableTabs.splice(tabIndex, 1);
      if (editableTabs.length) {
        editableTabsValue.value = editableTabs[0].name;
        navigateToRoute(editableTabs[0].name);
      } else {
        editableTabsValue.value = '';
        router.push('/home'); // 默认路由
      }
    }
  }
  // 如果需要处理 'add' 动作，可以在这里添加逻辑

};
//处理标签页点击
const handeTabsClick = (pane: TabsPaneContext, ev: Event) => {
  editableTabsValue.value = pane.paneName?.toString() || '';
  activeMenu.value = pane.paneName?.toString() || '';
  navigateToRoute(pane.paneName?.toString() || '');
};

// 监听路由变化，自动选中对应的 tab
watch(
  () => route.path,
  (newPath) => {
    if (newPath === '/home') {
      editableTabsValue.value = '';
      activeMenu.value = '';
      return;
    }
    const existingTab = editableTabs.find((tab) => tab.name === newPath);
    if (existingTab) {
      editableTabsValue.value = existingTab.name;
      activeMenu.value = newPath;
    } else {
      handleMenuSelect(newPath);
      activeMenu.value = newPath;
    }
  },
  { immediate: true }
);

// 定义一个枚举来管理命令类型，以增强代码的可读性和易维护性
enum Command {
  PersonInfo = 'personInfo',
  Logout = 'logout',
  UpdateInfo = 'updateInfo',
  UpdatePwd = 'updatePwd'
}
const handleCommand = async (command: Command) => {
  
  switch (command) {
    case Command.PersonInfo:
      await handlePersonInfo();
      break;
    case Command.Logout:
      await handleLogout();
      break;
    case Command.UpdateInfo:
      await handleUpdateInfo();
      break;
    case Command.UpdatePwd:
      await handleUpdatePwd();
      break;

  }
};
// 处理用户退出登录的逻辑
async function handleLogout() {
  try {
    await ElMessageBox.confirm(
      '你确认退出登录吗？',
      '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    // 用户确认退出
    await Userlogout();

    tokenStore.removeToken();      // 清空token
    userStore.removeUserInfo();  // 清空用户信息
    ElMessage.success('退出登录成功');
    router.push('/login');              // 跳转到登录页面

  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作
      ElMessage({
        type: 'info',
        message: '已撤销该操作'
      });
    } else {
  
      ElMessage.error('退出登录失败');
    }
  }
}
const dialogForm = ref<FormInstance>()
  const userForm = ref<UserDTO>({})
const showUserInfoDialog = ref(false)
const showChangePasswordDialog = ref(false)
const dialogVisible = ref(false)
// 存储密码输入
const passwords = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const handleSubmit = async () => { 
  await updatePwd(passwords.value);
  showChangePasswordDialog.value = false;
  ElMessage.success('修改成功，请重新登录！');
  userStore.removeUserInfo()
  tokenStore.removeToken()
  router.push('/login')
}


const handlePersonInfo = async () => {
  
  showUserInfoDialog.value = true;
  userForm.value = userStore.userInfo;
};

const handleUpdateInfo = async () => {
  dialogVisible.value = true;
  userForm.value=userStore.userInfo;
}

const handleUpdatePwd = async () => {
  showChangePasswordDialog.value = true;
  
}
const update = async () => {
  // 更新逻辑
  try {
    const valid = await dialogForm.value?.validate();
    if (valid) {
      await updateUser(userForm.value)
      ElMessage.success('更新成功');
      dialogVisible.value=false;
    } else {
      // 验证失败的情况下，显示错误信息
      ElMessage.error('请检查输入项');

    }
  } catch (error) {
    // 捕获验证失败时的错误
    ElMessage.error('验证失败，请检查输入项');

  }
}

const handleClose = (done: () => void) => {
  dialogVisible.value = false
  // 重置验证规则，避免触发验证 需要用setTimeout包裹
  setTimeout(() => {
    dialogForm.value?.clearValidate()
  }, 100)
  done()
}
const rules = reactive<FormRules<UserDTO>>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
    ],
    phone:[
        { required: true, message: '请输入手机号', trigger: 'blur' },
    ],
    email:[
        { required: true, message: '请输入邮箱', trigger: 'blur' },
    ],
});


//与子组件通信
const isDialogOpen = ref(false);
function handleDialog(status: boolean) {
  isDialogOpen.value = status;
}
const headerStyle = computed(() => ({
  left: isCollapse.value ? '68px' : '220px',
  width: isCollapse.value ? 'calc(100% - 68px)' : 'calc(100% - 220px)'
}));
</script>
<style lang="scss" scoped>
/* 全局 box-sizing */
*,
*::before,
*::after {
  box-sizing: border-box;
}

/* 使根布局占满整个视口高度和宽度 */
.common-layout {
  height: 100vh;
  /* 视口高度 */
  width: 100vw;
  /* 视口宽度 */
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

/* 使 el-container 在根布局中占满剩余空间 */
.el-container {
  flex: 1;
  height: 100%;
  width: 100%;
  background-color: #f5f5f5;
}

.el-right {
  align-items: stretch;

  /* 让子元素宽度填满父容器 */
  .main-container {
    padding: 10px;

    .el-tabs {
      padding: 10px;
      background-color: #ffffff;
      border-radius: 15px;

    }
  }

}



/* 页头样式 */
.app-header {


  display: flex;
  flex-direction: column;
  /* 允许包含 header-content 和 header-tabs */
  justify-content: space-between;
  padding: 0 20px;
  height: 110px;

  /* 毛玻璃效果 */
  background-color: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(5px);
  background-size: 4px 4px;
  position: fixed;
  /* 固定在顶部 */
  z-index: 1000;
  /* 确保在最上层 1000表示优先级 */

}

.header-content {
  display: flex;
  margin-top: 3px;
  justify-content: space-between;
  /* 两端对齐 */
  align-items: stretch;
  flex: 1;
  /* 让 header-content 占据可用空间 */
  width: 100%;
  /* 仅设置下边框 */
  border-bottom: 1px solid #dedef7;

  h1 {
    margin: 0;
    font-size: 24px;
  }

  .el-icon {
    color: #5f5f66;
  }

  .el-dropdown__box {
    display: flex;
    cursor: pointer;
    transition: background-color 0.3s ease;

    &:hover {
      background-color: #f5f7f8;
    }

    .el-avatar {
      margin-left: 2px;

    }
  }
}

// 悬浮效果
.el-avatar {
  transition: transform 0.3s ease;

  &:hover {
    transform: scale(1.1);
  }
}

.el-dropdown-menu {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 10px 0;

  .el-dropdown-item {
    padding: 10px 20px;
    color: #333;
    font-size: 14px;
    display: flex;
    align-items: center;
    transition: background-color 0.3s ease, color 0.3s ease;

    &:hover {
      background-color: #409eff;
      color: #fff;
      cursor: pointer; //设置鼠标样式
    }

    &.is-active {
      background-color: #409eff;
      color: #fff;
    }

    .el-icon {
      margin-right: 8px;
    }
  }
}

// 标签页样式
.custom-tabs {
  margin-top: 8px;
}

:deep(.custom-tabs .el-tabs__item) {
  /* 默认标签文字颜色 */
  color: #4b4a4d;

  /* 标签文字大小 */
  font-size: 16px;

  /* 标签文字加粗   font-weight: bold;*/

  /* 过渡效果 */
  transition: color 0.3s ease;
}

:deep(.custom-tabs .el-tabs__item.is-active) {
  /* 选中标签的文字颜色 */
  color: #7b5dc3;
}

:deep(.custom-tabs .el-tabs__item:hover) {
  /* 鼠标悬停时的文字颜色 */
  color: #7b5dc3;
}

:deep(.custom-tabs .el-tabs__active-bar) {
  /* 选中标签下方指示器的颜色 */
  background-color: #409EFF;
}

/* Sidebar.scss */

$primary-color: #fbfbfb;
$active-color: #e5ddfb;
$menu-font-color: #434343;
$menu-icon-color: #434343;

.app-aside {
  background-color: $primary-color;
  /* 紫色，85% 透明度 */
  color: #3e3b3b;
  font-weight: bold;
  //transition: width 0.3s ease;

  h3 {
    color: #434343;
    text-align: center;
    padding: 20px 0;
    font-size: 1.5em;
    margin: 0;
  }

  .el-menu-vertical-demo {
    background-color: $primary-color;
    /* 继承父元素的背景色 */
    border-right: none;

    .el-menu-item,
    .el-sub-menu {
      color: $menu-font-color;
      background-color: $primary-color;
      transition: background-color 0.3s ease, color 0.3s ease;

    }

    .el-menu-item.is-active,
    .el-sub-menu.is-active>.el-sub-menu__title {
      background-color: $active-color;
      /* 选中项稍微亮一点 */
      color: $menu-font-color;
    }

    .el-sub-menu__title {
      display: flex;

      .el-icon {
        margin-right: 15px;
        color: $menu-icon-color;
      }

      .fonts {
        color: $menu-font-color;
      }

    }

    .el-menu-item {
      display: flex;

      .el-icon {
        margin-right: 15px;
        color: $menu-icon-color;
      }


    }
  }

  /* 处理折叠状态 */
  &[class*="is-collapse"] {
    background-color: $primary-color;
    /* 保持相同的背景色 */

    .el-menu-vertical-demo {

      .el-menu-item,
      .el-sub-menu__title {
        text-align: center;

        .el-icon {
          margin-right: 0;
          font-size: 1.5em;
        }

        span {
          display: none;
          /* 隐藏文字，仅显示图标 */
        }
      }

      .el-menu-item.is-active,
      .el-sub-menu.is-active>.el-sub-menu__title {
        background-color: rgba(255, 255, 255, 0.2);
        /* 保持选中项颜色 */
      }
    }

    h3 {
      font-size: 1.2em;
    }
  }
}


.blur-background {
  filter: blur(5px);
  transition: filter 0.3s ease;
}

.info-row {
  text-align: left;
  margin-left: 20px;
  margin-top: 8px;
}
</style>
